<?php
namespace app\home\controller;

use app\common\model\Lottery2Log;
use app\common\model\UserLotteryLoading;

use app\common\component\user_wallet\UserWalletService;
use app\common\component\user_wallet_log\UserWalletLogService;
use app\common\component\lottery_2_log\Lottery2LogService;
use app\common\component\user_lottery_loading\UserLotteryLoadingService;

class GameLotteryTwo extends ControllerBase {
	public function _initialize() {
		$this -> checkLogin();
	}

	private function makeLog($currentTime) {
		(new Lottery2LogService()) -> makeLog($currentTime, $currentTime + getParamLottery('LOTTERY_2_OPEN_TIME') * 60, getParamLottery('LOTTERY_2_EACH_HIGH_BONUS'), 0, getParamLottery('LOTTERY_2_EACH_PRICE'));
	}

    public function index() {
    	(new Lottery2LogService()) -> handleLottery();
    	$currentTime = time();

		$LOTTERY_2_START_TIME = strtotime(getParamLottery('LOTTERY_2_START_TIME'));
		if($currentTime >= $LOTTERY_2_START_TIME) {
			$selectLottery2Log = Lottery2Log::where('create_time', 'egt', $LOTTERY_2_START_TIME) -> order('lottery_2_log_id DESC') -> select();

			$countLottery2Log = count($selectLottery2Log);
			if($countLottery2Log < getParamLottery('LOTTERY_2_TIMES')) {
				if(!isset($selectLottery2Log[0])) {
					$this -> makeLog($currentTime);
				} else if($selectLottery2Log[0] -> num != 0) {
					$this -> makeLog($currentTime);
				}
			}
		}

		$this -> view -> assign('showLotteryLog', Lottery2Log::order('lottery_2_log_id DESC') -> limit(2) -> select());

		$this -> view -> assign('lotteryLogs', Lottery2Log::where('num != 0') -> order('lottery_2_log_id DESC') -> paginate(10, true));

		$this -> view -> assign('userLotteryLoading', (new UserLotteryLoadingService()) -> getUserLotteryLoading(\think\Session::get('user_id')));
    	return $this -> view -> fetch();
	}

    public function sale() {
    	$lastLottery2Log = Lottery2Log::order('lottery_2_log_id DESC') -> find();
		if($lastLottery2Log -> num != 0) {
			echo '<meta charset="utf-8"><script>alert("当天投注已经结束!");window.location.href="/game/lottery/one";</script>';exit;
		}

		if(time() > $lastLottery2Log -> stop_time) {
			echo '<meta charset="utf-8"><script>alert("当期已投注截止，请等候开奖!");window.location.href="/game/lottery/one";</script>';exit;
		}

		$this -> view -> assign('lastLotteryLog', $lastLottery2Log);

		$this -> view -> assign('LOTTERY_MIN_NUM', getParamLottery('LOTTERY_2_MIN_NUM'));
		$this -> view -> assign('LOTTERY_MAX_NUM', getParamLottery('LOTTERY_2_MAX_NUM'));

    	return $this -> view -> fetch();
	}

    public function handleSale() {
    	$post = $this -> request -> post();

		$lastLottery2Log = Lottery2Log::order('lottery_2_log_id DESC') -> find();
		if(time() > $lastLottery2Log -> stop_time) {
			echo '<meta charset="utf-8"><script>alert("当期已投注截止，请等候开奖!");window.location.href="/game/lottery/one";</script>';exit;
		}

		$lastLottery2Log -> current_bonus += $lastLottery2Log -> each_num_price;
		if($lastLottery2Log -> current_bonus > $lastLottery2Log -> high_bonus ) {
			echo '<meta charset="utf-8"><script>alert("本期累计奖金已大于最高奖金!");window.history.go(-1);</script>';exit;
		}

		$userId = \think\Session::get('user_id');
		$numDetail = json_decode($lastLottery2Log -> num_detail, true);
		$issetNumDetail = isset($numDetail[$userId]);
		if($issetNumDetail && (count($numDetail[$userId]) >= getParamLottery('LOTTERY_2_EACH_USER_BUY_NUM'))) {
			echo '<meta charset="utf-8"><script>alert("您本期购买的号码大于指定数额!");window.history.go(-1);</script>';exit;
		}

		if($issetNumDetail && in_array($post['num'], $numDetail[$userId])) {
			echo '<meta charset="utf-8"><script>alert("此号码你已经购买，请勿重复购买!");window.history.go(-1);</script>';exit;
		}

		$resultUserWallet = (new UserWalletService) -> getUserWallet();
		if($lastLottery2Log -> each_num_price > $resultUserWallet['data']['user_wallet'] -> money) {
    		echo '<meta charset="utf-8"><script>alert("您的金钱不足!");window.history.go(-1);</script>';exit;
    	}

		\think\Db::startTrans();
		try {
			$resultUserWallet['data']['user_wallet'] -> money -= $lastLottery2Log -> each_num_price;
			if(!$resultUserWallet['data']['user_wallet'] -> save()) {
				throw new \Exception('金额或提现额度扣除失败');
			}

			$user_name = \think\Session::get('user_name');
			$resultUserWalletLog = (new UserWalletLogService) -> log(7, 0, $lastLottery2Log -> each_num_price, $user_name, '购买号码', 1, $user_name);
			if($resultUserWalletLog['code'] !== 0) {
				throw new \Exception($resultUserWalletLog['message']);
			}

			$userLotteryLoading = (new UserLotteryLoadingService()) -> getUserLotteryLoading($userId);
			$userLotteryLoading -> lottery_2_loading += 2;
			if(!$userLotteryLoading -> save()) {
				throw new \Exception('投注失败,userLotteryLoading');
			}

			if($issetNumDetail) {
				$numDetail[$userId][] = $post['num'];
			} else {
				$numDetail[$userId] = [];
				$numDetail[$userId][] = $post['num'];
			}

			$lastLottery2Log -> num_detail = json_encode($numDetail);
			if(!$lastLottery2Log -> save()) {
				throw new \Exception('投注失败,lastLottery2Log');
			}

			\think\Db::commit();
		} catch(\Exception $e) {
			\think\Db::rollback();

			echo '<meta charset="utf-8"><script>alert("' . $e -> getMessage() . '!");window.history.go(-1);</script>';exit;
		}

		echo '<meta charset="utf-8"><script>alert("投注成功!");window.location.href="/game/lottery/one";</script>';exit;
	}
}